<?php
namespace App\Http\Controllers\Client;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Carbon\Carbon;

class ReplyController extends Controller
{
  //上传图片ajax
  public function ajaxupload(Request $request){
      $path = $request->file('file')->storeAs('public/coser_img','coser_'.time().rand(1,99));
      $path = strchr($path,'/');
      if($request->session()->has('path')){
        $path_1 = session('path');
        $path = $path_1.'#'.$path;
      }
      session(['path'=>$path]);
  }
  //发布帖子
  public function createArticle(Request $request)
  {
    $path = session('path');
    $request->session()->forget('path');
    $this->validate($request, [
      'content' => 'required|min:10|max:255',
    ]);
    $ident = session('ident');
    $user_id = DB::table('users')->select('id')->where('ident','=',$ident)->get();
    $content = $request->content;
    $incognito = isset($request->incognito) ? $request->incognito : "0";
    $nowtime = Carbon::now('Asia/Shanghai');
    $res = DB::table('article')->insert([
      'user_id'=>$user_id[0]->id,
      'content'=>$content,
      'incognito'=>$incognito,
      'content_pic'=>$path,
      'create_time'=>$nowtime,
    ]);
    if($res){
      session(['path'=>null]);
      session()->flash('success','发布成功,审核通过即可在网站上展示');
      return redirect('/');
    }
  }

  //回复帖子
  public function createReply(Request $request)
  {
    $this->validate($request, [
      'reply' => 'required|min:2|max:45',
    ]);
    $ident = session('ident');
    $userarr = DB::table('users')->select('id')->where('ident','=',$ident)->get();
    $user_id = $userarr[0]->id;
    $article_id = $request->article_id;
    $nowtime = Carbon::now('Asia/Shanghai');
    $res = DB::table('reply')->insert([
      'article_id'=>$article_id,
      'user_id'=>$user_id,
      'reply'=>$request->reply,
      'create_time'=>$nowtime,
    ]);
    if($res){
      DB::table('article')->where('id','=',$request->article_id)->increment('replynum');
      session()->flash('alert','回复成功');
      return redirect("/article/$article_id");
    }
  }
}
